package fhq.hcmute.edu.vn.util;

import java.awt.image.BufferedImage;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;

import fhq.hcmute.edu.vn.network.ComputerInfos;

public final class BarcodeUtil {
	private BarcodeUtil() {

	}

	public static BufferedImage encode(final ComputerInfos serverInfo) {
		int width = 290;
		int height = 290;
		BitMatrix bitMatrix;
		String text = serverInfo.toString();
		try {
			bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE,
					width, height, null);
			return MatrixToImageWriter.toBufferedImage(bitMatrix);
		} catch (WriterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static void decode(final BufferedImage bufferedImage) {
		Result result;
		try {
			HybridBinarizer source = new HybridBinarizer(
					new BufferedImageLuminanceSource(bufferedImage));
			BinaryBitmap image = new BinaryBitmap(source);
			MultiFormatReader multiFormatReader = new MultiFormatReader();
			result = multiFormatReader.decode(image);
			BarcodeFormat barcodeFormat = result.getBarcodeFormat();
			System.out.println(barcodeFormat.ordinal());
			System.out.println(result.getText());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
